package list;

/**
 * @author way
 * @create 2025-02-06 15:49
 */
public class _160_getIntersectionNode {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;

        ListNode curA = headA;
        ListNode curB = headB;
        int lenA = 0;
        int lenB = 0;
        while (curA.next != null) {
            lenA++;
            curA = curA.next;
        }

        while (curB.next != null) {
            lenB++;
            curB = curB.next;
        }
        curA = headA;
        curB = headB;
        int n = Math.abs(lenA - lenB);

        if (lenA > lenB) {
            for (int i = 0; i < n; i++) {
                curA = curA.next;
            }
        } else {
            for (int i = 0; i < n; i++) {
                curB = curB.next;
            }
        }

        while (curA != null) {
            if (curA == curB) {
                return curA;
            } else {
                curA = curA.next;
                curB = curB.next;
            }
        }

        return null;
    }
}
